<style scoped lang="less">
.defaultStyle {
  width: 63.8px;
  padding: 0;
  box-sizing: border-box;
}
.iconStyle {
  width: 50px;
  padding: 0 15px;
  box-sizing: content-box;
}
</style>
<template>
  <a-form
    :model="queryParams"
    layout="inline"
    autocomplete="off"
    @finish="onFinish"
    class="s-search"
  >
    <a-row class="s-search-row">
      <a-col class="s-search-col">
        <a-form-item :label="t('sysMenu29')" name="name">
          <a-input
            allowClear
            v-model:value="queryParams.name"
            :placeholder="t('placeholder148')"
            v-input.trim.textFilter
          >
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-space :size="16">
            <a-button type="primary" html-type="submit">
              {{ t("base.query") }}
              <template #icon><search-outlined /></template>
            </a-button>
            <a-button type="default" @click="handleReset"
              >{{ t("base.reset") }}
              <template #icon><delete-outlined /></template>
            </a-button>
          </a-space>
        </a-form-item>
      </a-col>
      <a-row :gutter="16">
        <a-col>
          <a-spin :spinning="importLoading">
            <upload-button
              v-has="'menuApi.import'"
              :uploadText="t('base.import')"
              :modelValue="fileJson"
              @update:modelValue="importFile"
              :class="
                getSelfNodeIcon('menuApi.import') ? 'iconStyle' : 'defaultStyle'
              "
            >
              <template #icon>
                <i
                  v-if="getSelfNodeIcon('menuApi.import')"
                  :class="`s-icon iconfont ${getSelfNodeIcon(
                    'menuApi.import'
                  )}`"
                />
              </template>
            </upload-button>
          </a-spin>
        </a-col>
        <a-col>
          <a-button @click="exportFile" v-has="'menuApi.export'">
            {{ t("base.export") }}
            <template #icon>
              <i
                :class="`s-icon iconfont ${getSelfNodeIcon('menuApi.export')}`"
              />
            </template>
          </a-button>
        </a-col>
        <a-col>
          <a-button
            v-has="'menuApi.create'"
            type="primary"
            @click="handleAction('add')"
            >{{ t("base.add") }}
            <template #icon>
              <i
                :class="`s-icon iconfont ${getSelfNodeIcon('menuApi.create')}`"
              />
            </template>
          </a-button>
        </a-col>
      </a-row>
    </a-row>
  </a-form>
  <a-table
    :loading="tableLoading"
    class="s-table"
    :pagination="false"
    :columns="columns"
    rowKey="id"
    :data-source="tableData"
    :indent-size="40"
    childrenColumnName="children"
  >
    <template v-slot:headerCell="{ title, column }">
      <template v-if="column.key === 'id'">
        <div class="s-table-header_cell">{{ title }}</div>
      </template>
    </template>
    <template v-slot:bodyCell="{ value, text, index, column, record }">
      <template v-if="column.key === 'visible'">
        <a-tag color="#108ee9" v-if="value === 0">{{ t("sysMenu27") }}</a-tag>
        <a-tag color="#87d068" v-if="value === 1">{{ t("sysMenu28") }}</a-tag>
      </template>
      <template v-if="column.key === 'is_menu'">
        <a-tag color="blue" v-if="value === 0">{{ t("sysMenu19") }}</a-tag>
        <a-tag color="cyan" v-if="value === 1">{{ t("sysMenu20") }}</a-tag>
        <a-tag color="green" v-if="value === 2">{{ t("sysMenu21") }}</a-tag>
        <a-tag color="orange" v-if="value === 3">{{ t("sysMenu22") }}</a-tag>
      </template>

      <template v-if="column.key === 'action'">
        <div class="s-table-body_cell">
          <div v-has="'menuApi.update'">
            <a-button type="link" @click="handleAction('edit', record)"
              >{{ t("base.edit") }}
              <template #icon>
                <i
                  :class="`s-icon iconfont ${getSelfNodeIcon(
                    'menuApi.update'
                  )}`"
                />
              </template>
            </a-button>
            <a-divider type="vertical" />
          </div>
          <a-button
            v-has="'menuApi.delete'"
            type="link"
            @click="handleDelete(record)"
            >{{ t("base.delete") }}
            <template #icon>
              <i
                :class="`s-icon iconfont ${getSelfNodeIcon('menuApi.delete')}`"
              />
            </template>
          </a-button>
        </div>
      </template>
    </template>

    <template v-slot:expandIcon="{ record, onExpand, expanded }">
      <div style="display: flex">
        <div v-if="record?.children?.length">
          <a-space
            :size="5"
            style="white-space: nowrap; cursor: pointer"
            @click="(e) => onExpand(record, e)"
          >
            <span v-if="expanded">
              <caret-down-outlined />
            </span>
            <span v-else>
              <caret-right-outlined />
            </span>
            <span>{{ record.id }}</span>
          </a-space>
        </div>
        <span v-else>{{ record.id }}</span>
      </div>
    </template>
  </a-table>
  <IMFormInline @refreshTable="refreshTable" ref="drawerRef" />
</template>
<script lang="tsx" setup>
import { IMTableType } from "@/types/table";
import IMFormInline from "./components/drawer/index.vue";
import {
  formInline,
  operateType,
  treeDataOptions,
  tableLoading,
  set_formInline,
  findParentNode,
} from "./store";
import { deelTreeData } from "./utils";
import { saveAs } from "file-saver";
import styles from "./index.module.less";
import { getSelfNodeIcon } from "@system/menu/store";
import { QueryParamsType } from "./type";
const tableData = ref<any>([]);
const t = $t;
const _this = reactive<any>(getCurrentInstance());
const columns = reactive<IMTableType[]>(
  defineColumns([
    {
      title: computed(() => `${$t("table194")}id`),
      key: "id",
      customCell: (record, rowIndex, column) => {
        const parentNode = findParentNode(tableData.value, record.parent_id);
        let className = "";
        switch (parentNode?.is_menu) {
          case 0:
            className = styles.cell_1;
            break;
          case 1:
            className = styles.cell_2;
            break;
          case 2:
            className = styles.cell_3;
            break;
          default:
            className = styles.cell_0;
            break;
        }
        return {
          class: className,
        };
      },
    },
    {
      title: computed(() => `${$t("table195")}id`),
      dataIndex: "parent_id",
      key: "parent_id",
    },
    {
      title: getProxyT("table196"),
      dataIndex: "name",
      key: "name",
    },
    {
      title: getProxyT("table197"),
      dataIndex: "slug",
      key: "slug",
    },
    {
      title: getProxyT("table233"),
      dataIndex: "icon",
      key: "icon",
      customRender: ({ text, record, index, column }: any) => (
        <i class={["iconfont", text]}></i>
      ),
    },
    {
      title: getProxyT("table198"),
      dataIndex: "is_menu",
      key: "is_menu",
    },
    {
      title: getProxyT("table31"),
      dataIndex: "visible",
      key: "visible",
    },
    {
      title: getProxyT("table199"),
      dataIndex: "sort",
      key: "sort",
    },
    {
      title: computed(() => `HTTP${$t("table200")}`),
      dataIndex: "http_method",
      key: "http_method",
    },
    {
      title: getProxyT("table201"),
      dataIndex: "http_path",
      key: "http_path",
    },
    {
      title: getProxyT("table43"),
      dataIndex: "create_time",
      key: "create_time",
      customRender: ({ text }: any) => getTimeByZone(text),
    },
    {
      title: getProxyT("table202"),
      dataIndex: "update_time",
      key: "update_time",
      customRender: ({ text }: any) => getTimeByZone(text),
    },
    { title: getProxyT("base.action"), key: "action", align: "center" },
  ])
);
const queryParams = reactive<QueryParamsType>({ name: undefined });
const handleReset = () => {
  clearObjAttr(queryParams);
  refreshTable();
};
const onFinish: any = (values: any) => {
  onFinish.timer && clearTimeout(onFinish.timer);
  onFinish.timer = setTimeout(() => refreshTable(), 200);
};
const fetchList = async () => {
  try {
    tableLoading.value = true;
    tableData.value = [];
    const res: any = await menuApi.queryAllMenu({
      ...queryParams,
    });
    if (res.code !== 200) return message.error(res.message);
    tableData.value = deelTreeData(res?.data ?? []);
    treeDataOptions.value = tableData.value;
    return res;
  } catch (error: any) {
    message.error(error.message);
  } finally {
    tableLoading.value = false;
  }
};
const refreshTable = async () => await fetchList();
const handleAction = async (type: string, record?: any) => {
  operateType.value = type;
  _this.refs.drawerRef.showDrawer();
  set_formInline(type, formInline, record);
};
const deleteDataById = async (id: any) => {
  try {
    const res: any = await menuApi.delete({
      id: id,
    });
    if (res.code != 200) return message.error(res.message);
    refreshTable();
    message.success($t("base.deleteSuccess"));
  } catch (error: any) {
    message.error(error.message);
  }
};
const handleDelete = (record: any = {}) => {
  Modal.confirm({
    closable: true,
    title: `${$t("sysMenu31")}`,
    content: `${$t("sysMenu32")}"${record.name}"${$t("sysMenu33")}`,
    icon: null,
    centered: true,
    onOk: () => deleteDataById(record.id),
    cancelText: $t("base.cancel"),
    onCancel: () => Modal.destroyAll(),
  });
};
watch(
  () => sysZone.value,
  () => fetchList()
);
onActivated(() => fetchList());
const exportFile = () => {
  if (!tableData.value.length) return;
  const blob = new Blob([JSON.stringify(tableData.value)], {
    type: "text/plain;charset=utf-8",
  });
  saveAs(blob, `menus-${generateRandomString(8)}.json`);
};
const importLoading = ref(false);
const fileJson = ref("");
const importFile = (fileObject) => (fileJson.value = fileObject);
</script>
